<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ name: 'home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="content">
      <!-- 头部功能 -->
      <template #header>
        <div>
          <el-button type="primary" size="medium">添加角色</el-button>
        </div>
      </template>
      <!-- 正文内容 -->
      <el-table
        ref="treeTable"
        :data="roles"
        style="width: 100%"
        border
        size="small"
        v-loading="loading"
        row-key="id"
        :tree-props="{children:'a'}"
        :expand-row-keys="exArr"
        @expand-change="expandChange"
      >
        <template #empty>
          <el-empty description="暂无数据"></el-empty>
        </template>
        <el-table-column
          type="expand"
          label="明细"
          width="60px"
          #default="{ row }"
        >
          <el-empty
            v-if="!row.children || row.children.length == 0"
            :image-size="40"
            description="未分配权限"
          ></el-empty>
          <!-- 参考代码 -->
          <RolesTreeList
            class="role-box"
            :list="row.children"
            caret
            #default="itemB"
          >
            <RolesTreeList
              :list="itemB.list"
              type="success"
              caret
              #default="itemC"
            >
              <RolesTreeList :list="itemC.list" type="warning"></RolesTreeList>
            </RolesTreeList>
          </RolesTreeList>
          <!-- 参考代码 -->
        </el-table-column>
        <el-table-column type="index" label="序号" width="60px">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300px" #default="{ row }">
          <el-button type="primary" size="mini" icon="el-icon-edit"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="removeRolesById(row.id)"
            >删除</el-button
          >
          <el-button
            type="warning"
            size="mini"
            icon="el-icon-setting"
            @click="showSettingModel(row.children,row.id)"
            >分配权限</el-button
          >
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限 -->
    <el-dialog title="角色权限分配" :visible.sync="rulesSetting">
      <el-tree
        ref="rightsTree"
        :data="rights"
        show-checkbox
        default-expand-all
        node-key="id"
        highlight-current
        :props="{ label: 'authName' }"
      >
      </el-tree>
      <template #footer>
        <span>
          <el-button @click="rulesSetting = false">取 消</el-button>
          <el-button type="primary" @click="setRuleRights()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分配权限 -->
  </div>
</template>

<script>
import RolesTreeList from "@/components/RolesTreeList.vue";
export default {
  components: {
    RolesTreeList,
  },
  data() {
    return {
      // ===
      loading: false,
      query: "",
      roles: [],
      // ==== 权限分配相关
      rulesSetting: false,
      rights: [],
      rulesSettingRid:null,
      // ====
      exArr:[],
      tempExArr:[]
    };
  },
  methods: {
    expandChange(row,rows){
      // console.log(row);
      // console.log(rows);
      let temp = [];
      rows.forEach(item => {
        // console.log(item.id)
        temp.push(item.id)
      });
      this.tempExArr = temp;
    },
    async loadRolesListPage() {
      try {
        this.loading = true;
        let result = await this.$api.getRolesList();
        if (result == "error") return;
        this.roles = result;
        this.$nextTick(()=>{
          // 断开引用指向
          this.exArr = [ ...this.tempExArr ];
        })
      } catch (error) {
        console.log("RolesView-loadRolesListPage-error:", error);
      } finally {
        this.loading = false;
      }
    },
    async removeRolesById(id) {
      try {
        console.log(id);
        // if (result == "error") return;
        // this.$message.success("删除成功");
        // let lastFlag = this.total%this.pagesize==1;
        // let lastPageFlag = Math.ceil(this.total/this.pagesize)==this.pagenum;
        // if(lastFlag&&lastPageFlag&&this.pagenum!=1){
        //   this.pagenum = this.pagenum - 1;
        // }
        // this.loadRolesListPage();
      } catch (error) {
        console.log("RolesView-removeRolesById-error:", error);
      }
    },
    // ==== 权限分配
    showSettingModel(ruleRights,rid){
      this.rulesSetting = true;
      this.rulesSettingRid = rid;
      this.$nextTick(()=>{
        console.log(ruleRights)
        // console.log(this.$refs.rightsTree)
        // console.log(this.$refs)
        this.$refs.rightsTree.setCheckedNodes(ruleRights)
      })
    },
    // === 初始化所有权限的加载
    async initRulesList() {
      try {
        let rights = await this.$api.getRightsList("tree");
        if (rights == "error") return;
        // console.log(rights);
        this.rights = rights;
      } catch (error) {
        console.log("RolesView-initRulesList-error:", error);
      }
    },
    // 设置角色权限
    async setRuleRights(){
       try {
        let halfKeys = this.$refs.rightsTree.getHalfCheckedKeys()
        let keys = this.$refs.rightsTree.getCheckedKeys()
        // console.log(keys,halfKeys);
        let rightIds = halfKeys.concat(keys).join(",")
        console.log(rightIds)

        let result = await this.$api.updateRoleRights(this.rulesSettingRid,{
          rids:rightIds
        })
        if (result == "error") return;
        
        this.$notify({
          title: '角色授权成功',
          type: 'success'
        });
        this.rulesSetting = false;
        this.loadRolesListPage();
      } catch (error) {
        console.log("RolesView-setRuleRights-error:", error);
      }
    }
  },
  created() {
    this.loadRolesListPage();
    this.initRulesList();
  },
};
</script>


<style lang="less" scoped>
.content,
.el-pagination {
  margin-top: 20px;
}
.search-input {
  width: 300px;
}
.add-btn {
  margin-left: 20px;
}
.tip {
  font-size: 18px;
}
.tip.el-icon-error {
  color: red;
}
.tip.el-icon-success {
  color: green;
}
</style>